package com.ihrm.system.shiro.realm;

import com.ihrm.common.realm.IhrmRealm;
import com.ihrm.domain.system.Permission;
import com.ihrm.domain.system.User;
import com.ihrm.domain.system.response.ProfileResult;
import com.ihrm.system.service.PermissionService;
import com.ihrm.system.service.UserService;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 小伟
 * @version V1.0
 * @Package com.ihrm.common.realm
 * @date 2020/12/21 16:44
 * @Copyright © 2020-2021 郑州恒星科技有限责任公司
 * 自定义用户realm
 */
public class UserRealm extends IhrmRealm {
    @Override
    public void setName(String name) {
        super.setName("userRealm");
    }

    @Autowired
    UserService userService;
    @Autowired
    PermissionService permissionService;
    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String mobile = upToken.getUsername();
        String password = new String(upToken.getPassword());
        User user = userService.findByMobile(mobile);
        if (user != null && password.equals(user.getPassword())) {
            ProfileResult result = null;
            if ("user".equals(user.getLevel())) {
                result = new ProfileResult(user);
            } else {
                Map<String, Object> map = new HashMap<>();
                if ("coAdmin".equals(user.getLevel())) {
                    map.put("enVisible", "1");
                }
                List<Permission> list = permissionService.findAll(map);
                result = new ProfileResult(user, list);
            }
            return new SimpleAuthenticationInfo(result, user.getPassword(), this.getName());
        }
        return null;
    }
}
